package cn.guozeyiblog.client;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import cn.guozeyiblog.client.SearchActivity.AsyGetBlogList;
import cn.guozeyiblog.netutils.HttpUtil;
import cn.guozeyiblog.netutils.NetWorkStatus;

public class UpdateActivity extends Activity implements OnClickListener{

	private TextView current_version;
	private int current_versioncode;
	private TextView new_version;
	private int new_versioncode;
	private String downloadurl;
	private String downloadpath;
	private Button checkUpdate;
	private ProgressBar bar;
	private String apkpath;
	private AlertDialog dialog;
	private View view;
	private final static int NO_UPDATE =1;
	private final static int HAVE_UPDATE =2;
	private final static int ERROR =-1; //状态码错误 不是200
	private final static int DOWNLOAD_EDN=3;
	private final static int CHANGE_PROGRESS=4;
	private Handler hander=new Handler(){
		public void handleMessage(android.os.Message msg) {
			bar.setVisibility(View.GONE);
			switch (msg.what) {
			case NO_UPDATE:
				Toast.makeText(getApplicationContext(), "你已是最新的版本,不需要更新", 0).show();
				checkUpdate.setClickable(false);
				checkUpdate.setText("没有更新");
				break;
			case HAVE_UPDATE:
				Toast.makeText(getApplicationContext(), "有新的版本可得到", 0).show();
				checkUpdate.setText("下载更新");
				break;
			case ERROR:
				Toast.makeText(getApplicationContext(), "网络有点小错误,你可以稍后再试", 0).show();
				break;
			case DOWNLOAD_EDN:
				dialog.dismiss();
				Toast.makeText(getApplicationContext(), "下载完成,自动安装", 0).show();
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(new File(apkpath)), "application/vnd.android.package-archive");
				startActivity(intent);
				break;
			case CHANGE_PROGRESS:
                dialog.setMessage("已下载:"+(int)(msg.obj)+"%");
				break;
			default:
				break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.updateactivity);
		initView();
		checkUpdate.setOnClickListener(this);
		try {
			PackageInfo info = getPackageManager().getPackageInfo("cn.guozeyiblog.client", PackageManager.GET_ACTIVITIES);
			System.err.println("Version:--------------------->"+info.versionCode);
			current_versioncode = info.versionCode;
			if(NetWorkStatus.isNetworkAvailable(getApplicationContext())){
				new AsyGetNewVersion().execute("http://kutear.sinaapp.com/version.php");
			}else {
				Toast.makeText(getApplicationContext(), "你的网络不可用哦", 0).show();
			}
			
			//Toast.makeText(getApplicationContext(), info.versionCode+"", 0).show();
			current_version.append(" "+current_versioncode);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		view = ((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dialog, null);
		initDialog();
	}

	private void initView(){
		current_version = (TextView) findViewById(R.id.current_version);
		new_version = (TextView) findViewById(R.id.new_version);
		checkUpdate = (Button) findViewById(R.id.check_update);
		bar = (ProgressBar) findViewById(R.id.update_progressBar1);
	}

	private void initDialog(){
	  dialog = new ProgressDialog(UpdateActivity.this);
	  dialog.setTitle("下载进度");
	  dialog.setIcon(R.drawable.ic_launcher);
	  dialog.setMessage("已下载:");
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		//下载 
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			downloadpath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Emlog";
			File file = new File(downloadpath);
			if (!file.exists()) {
				file.mkdir();
			}
			System.out.println(downloadpath);
		}else {
			Toast.makeText(getApplicationContext(), "没有外部存储", 0).show();
			return;
		}
		checkUpdate.setClickable(false);
		dialog.show();
		new Thread(){
			public void run() {
			  try {
				URL url = new URL(downloadurl); //app's link
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.setConnectTimeout(5000);
				InputStream in = connection.getInputStream();
				int filesize = connection.getContentLength();
				System.out.println("------filesize::"+filesize);
				String appname = downloadurl.substring(downloadurl.lastIndexOf("/"), downloadurl.length());
				File file_out = new File(downloadpath+"/"+appname);
				apkpath = file_out.getAbsolutePath();
				FileOutputStream outputStream = new FileOutputStream(file_out);
				byte b[] = new byte[1024];
				int c;
				int progress=0;
				while((c=in.read(b))!=-1){
					outputStream.write(b, 0, c);
					progress+=c;
					System.out.println("---进度---"+(100*(progress)/filesize));
					Message msg = new Message();
					msg.what = CHANGE_PROGRESS;
					msg.obj = (100*(progress)/filesize);
					hander.sendMessage(msg);
				}
				outputStream.flush();
				in.close();
				outputStream.close();
				connection.disconnect();
				hander.sendEmptyMessage(DOWNLOAD_EDN);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
			};
		}.start();
	}

	public class AsyGetNewVersion extends AsyncTask<String, Void, Integer>{

		@Override
		protected Integer doInBackground(String... params) {
			String result = HttpUtil.httpGet(params[0]);
			//System.out.println(result);
			//解析Json数据
			if(result.equals("")||result==null){
				return null;
			}
			try {
				JSONObject object = new JSONObject(result);
				int status = object.getInt("status");
				if (status==200) {
					JSONArray array = object.getJSONArray("info");
					JSONObject ob = array.getJSONObject(0);
					System.out.println("-------APP_NAME--------"+ob.getString("APP_NAME"));
					System.out.println("-------APP_VERSION-----"+ob.getString("version"));
					new_versioncode = ob.getInt("version");
					System.out.println("-------APP_DOWNLOADURL-"+ob.getString("download_url"));
					downloadurl = ob.getString("download_url");
					if (current_versioncode>=new_versioncode) {
						hander.sendEmptyMessage(NO_UPDATE);
					}else {
						hander.sendEmptyMessage(HAVE_UPDATE);
					}
				}else {
					hander.sendEmptyMessage(ERROR);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			publishProgress();
			return null;
		}


		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			new_version.append(" "+new_versioncode);
			super.onProgressUpdate(values);
		}
	}

}
